package com.fan.leetcode;

/**
 * 面试题 17.10. 主要元素
 *
 * @author ZhangFan
 * @since 2021/8/3 下午 10:27
 */
public class QuestionInterview17_10 {
    public int majorityElement(int[] nums) {
        int temp = 0;
        int count = 0;
        for (int num : nums) {
            if (count == 0) {
                temp = num;
            }
            if (temp == num) {
                count++;
            } else {
                count--;
            }
        }
        count = 0;
        for (int num : nums) {
            if (num == temp) {
                count++;
            }
        }
        if (count > nums.length / 2) {
            return temp;
        } else {
            return -1;
        }
    }
}
